package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.service.WebSocketServer;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author Katana
 * @date 2025-05-29
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    
    @Autowired
    private DeviceMapper deviceMapper;
    
    @Autowired
    private IAlertDataService alertDataService;
    
    @Value("${alertRule.roleAdmin}")
    private String managerRole;
    
    @Value("${alertRule.roleRepair}")
    private String deviceMaintainerRole;
    
    @Autowired
    private WebSocketServer webSocketServer;
    
    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }
    
    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }
    
    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }
    
    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }
    
    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }
    
    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }
    
    
    /**
     * 报警规则过滤
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void alterFilter() {
        // 第一层,报警规则和设备数据和基础校验处理
        //1 查询所有启用的报警规则
        List<AlertRule> alertRules = lambdaQuery().eq(AlertRule::getStatus, 1).list();
        //1.2 判断列表是否为空
        if (alertRules == null || alertRules.isEmpty()) {
            log.error("没有启用的报警规则,处理中断");
            return;
        }
        //2 从缓存中获取最新的设备上报数据
        List<Object> deviceDatas = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        //2.1 判断数据列表是否为空
        if (deviceDatas.isEmpty()) {
            log.error("没有设备上报数据,处理中断");
            return;
        }
        //2.2 对设备数据进行格式化处理,解析为设备数据对象
        
        List<DeviceData> deviceDataList = deviceDatas.stream()
                .flatMap(deviceData -> JSONUtil.toList((String) deviceData, DeviceData.class).stream())
                .collect(Collectors.toList());
        
        
        //3 遍历处理每条设备数据
        deviceDataList.forEach(this::getAlterRules);
        
    }
    
    /**
     * 第二层 处理每条上报数据：上报数据基础校验与全部规则查询
     */
    private void getAlterRules(DeviceData deviceData) {
        //判断当前上报的数据是否过时
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 6000) {
            log.error("上报数据过旧,放弃处理");
            return;
        }
        //1 寻找设备上报数据对应的产品报警规则
        List<AlertRule> allRuleList = this.lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getIotId, -1)
                .list();
        
        //2 寻找设备上报数据对应的物模型报警规则
        List<AlertRule> iotRuleList = this.lambdaQuery()
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getStatus, 1)
                .list();
        
        //3 合并并对报警规则进行去重
        allRuleList.addAll(iotRuleList);
        if (allRuleList.isEmpty()) {
            log.error("没有对应的报警规则,处理中断");
            return;
        }
        allRuleList = allRuleList.stream().distinct().collect(Collectors.toList());
        //4 遍历处理每条报警规则
        allRuleList.forEach(rule -> handleAlertRule(rule, deviceData));
        
    }
    
    /**
     * 第三层 处理每条报警规则,对每条规则数据进行规则判断
     */
    private void handleAlertRule(AlertRule alertRule, DeviceData deviceData) {
        //1 判断当前时间是否在报警规则的生效时间范围内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        if (startTime.isAfter(alarmTime) || endTime.isBefore(alarmTime)) {
            log.error("当前时间不在报警规则的生效时间范围内,处理中断");
            return;
        }
        //2 校验数据是否达到设置的报警阈值
        //2.1 设备上报的数据
        double dataValue = Double.parseDouble(deviceData.getDataValue());
        //2.2 规则设置的阈值
        Double value = alertRule.getValue();
        //2.3 比较运算符 >= 或 <
        String operator = alertRule.getOperator();
        //x大于y，结果就是1； x等于y，结果就是0； x小于y，结果就是-1
        int compare = NumberUtil.compare(dataValue, value);
        boolean shouldAlert = (compare >= 0 && ">=".equals(operator)) || (compare < 0 && "<".equals(operator));
        if (!shouldAlert) {
            log.error("当前数据不符合报警阈值,不应产生报警,处理中断");
            return;
        }
        
        //3 判断当前数据是否处于沉默期
        //3.1 获取当前设备的iotId
        String iotId = deviceData.getIotId();
        //3.2 从redis中获取沉默期数据
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if (silentData != null) {
            log.error("当前数据处于沉默期,处理中断");
            return;
        }
        
        //4 判断报警次数是否达到持续周期
        //统计次数的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        String aggData = redisTemplate.opsForValue().get(aggCountKey);
        //获取当前次数,默认为1,若有值则+1
        Long count = StringUtils.isEmpty(aggData) ? 1L : Integer.parseInt(aggData) + 1;
        //如果count与持续周期的值相等，则触发报警
        if (ObjectUtil.notEqual(count, alertRule.getDuration())) {
            //不相等,则将count写入redis中
            redisTemplate.opsForValue().set(aggCountKey, count + "");
            log.error("当前数据未达到持续周期,处理中断");
            return;
        }
        //5 触发报警,并找到需要处理报警的员工
        //5.1删除redis的报警数据
        redisTemplate.delete(aggCountKey);
        //5.2存储数据到沉默周期，设置一个过期时间，规则中的沉默周期
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        List<Long> userIds = new ArrayList<>();
        if (alertRule.getAlertDataType().equals(0)) {
            //老人异常数据
            if (deviceData.getLocationType().equals(0)) {
                //说明是报警手表，直接可以找到老人的id,通过老人id,找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            } else if (deviceData.getLocationType().equals(1) && deviceData.getPhysicalLocationType().equals(2)) {
                //说明是床位设备，可以通过床位id找到老人，通过老人id,找到对应的护理员
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            //设备异常数据，找维修工，或者是行政人员
            userIds = userRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }
        //无论是哪种情况，都要通知超级管理员
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);
        
        //6 保存报警数据
        insertAlertData(allUserIds, alertRule, deviceData);
        
        
    }
    
    private void insertAlertData(Collection<Long> userIds, AlertRule alertRule, DeviceData deviceData) {
        //1 构建报警数据
        AlertData alertData = new AlertData();
        //2 拷贝设备数据
        BeanUtils.copyProperties(deviceData, alertData);
        alertData.setAlertRuleId(alertRule.getId());
        //3 设置报警原因和其他信息
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                alertRule.getFunctionName(),
                alertRule.getOperator(),
                alertRule.getValue(),
                alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(alertRule.getAlertDataType());
        //4 遍历ids,为每个id创建一条报警数据
        List<AlertData> result = userIds.stream().map(userId -> {
            AlertData tempData = BeanUtil.toBean(alertData, AlertData.class);
            tempData.setUserId(userId);
            tempData.setId(null);
            return tempData;
        }).collect(Collectors.toList());
        
        //5 批量插入报警数据
        boolean saved = alertDataService.saveBatch(result);
        if (!saved) {
            log.error("批量保存报警数据失败");
        }
        
        //6 通过websocket发送报警信息消息给对应的用户
        result.forEach(x -> {
            //构建消息对象
            AlertNotifyVo alertNotifyVo = new AlertNotifyVo();
            BeanUtils.copyProperties(x, alertNotifyVo);
            alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
            alertNotifyVo.setFunctionName(alertRule.getFunctionName());
            alertNotifyVo.setAccessLocation(alertData.getRemark());
            alertNotifyVo.setNotifyType(1);
            
            //发送消息
            webSocketServer.notifyMsgToClient(x.getUserId().toString(), JSON.toJSONString(alertNotifyVo));
            
        });
    }
    
}









